package com.dys.ai.common.exception;

import com.dys.ai.common.api.ApiResponse;
import com.dys.ai.common.api.ResponseEntity;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Objects;

@Slf4j
@RestControllerAdvice(annotations = {RestController.class, Controller.class})
public class GlobalExceptionHandler {

    /**
     * 处理所有未捕获异常
     *
     * @param e 异常对象
     * @return api统一响应
     */
    @ExceptionHandler(value = Exception.class)
    public ResponseEntity handleException(Exception e,HttpServletRequest request) {
        log.error("请求路径: {}", request.getRequestURI());
        // 打印完整堆栈
        log.error("异常堆栈: ", e);
        return ApiResponse.error(500, "系统异常：" + e.getMessage());
    }

    /**
     * 处理自定义业务获异常
     *
     * @param ex 异常对象
     * @return api统一响应
     */
    @ExceptionHandler(value = CustomException.class)
    public ResponseEntity handleCustomException(CustomException ex) {
        if (Objects.isNull(ex.getCode())) {
            return ApiResponse.error(503, ex.getMessage());
        }
        return ApiResponse.error(ex.getCode(), "业务异常：" + ex.getMessage());
    }

    /**
     * 处理参数校验异常
     *
     * @param e 异常对象
     * @return api统一响应
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResponseEntity handleValidException(MethodArgumentNotValidException e) {
        String message = Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage();
        return ApiResponse.error(400, "参数错误：" + message);
    }

    /**
     * 处理空指针异常
     *
     * @param e 异常对象
     * @return api统一响应
     */
    @ExceptionHandler(value = NullPointerException.class)
    public ResponseEntity handleNullException(NullPointerException e) {
        return ApiResponse.error(500, "空指针异常：" + e.getMessage());
    }
}
